/**
 * Created by Administrator on 17-9-27.
 */
var io = require('socket.io');

var wsio = (function () {
    function wsio()
    {
    };
    wsio.prototype.newConnect= function (url,cb)
    {
        var opts = {
            'reconnection':false,
            'force new connection': true,
            'transports':['websocket']
        }
        //cc.log('callback in sio connect ',self.connectCallBack);
        var  sio = io.connect(url,opts);
        sio.eventMap={};
        sio.eventMap['onConnect']=cb;
//建立连接
        sio.onConnect=function()
        {   console.log('onConnect wsio ++++++++++++++++++++++');
            sio.sioConnected=true;
            var func=sio.eventMap['onConnect'];
            var self=this;
            this.tick=new Date().getTime();
            this.recvTick=new Date().getTime();
            sio.aliveTick=new Date().getTime();
            sio.timer=setInterval(function()
            {
                var time=(new Date().getTime()-self.tick)/1000;
                if(time>10)
                {   //console.log('socket timeout 10s ++++++++++++++++++++++++++++++++++++');
                    sio.tick=new Date().getTime();
                    //sio.sioConnected=false;
                    //if(sio.close)  sio.close();
                    //clearInterval(sio.timer);
                }
                var time1=(new Date().getTime()-sio.aliveTick)/1000;
                if(time1>=3)
                {
                    sio.aliveTick=new Date().getTime();

                }
            },500);
            if(func) func();
        }
        sio.sendLogin=function(data)
        {   console.log('send Login 71',JSON.stringify(data));
            sio.emit('login',data);
        },
        sio.send=function(data)
        {
            if(sio.sioConnected==false)
            {   console.log('已经断线了不能再发数据了');
                return;
            }
            if(data.event!='keepAlive')
            { console.log('send ',data);
            }
            //window.sio.emit('login',{msg:'hi',count:1000});
            sio.emit('action',data);
            //window.sio.emit('action',data);
        },

        sio.onDisconnect=function()
        {
            console.log('sio.onDisconnect ++++++++++++++++++++++++++++');
            sio.sioConnected=false;
            sio=null;
        }
        sio.onData=function(data)
        {
            sio.tick=new Date().getTime();
            sio.sioConnected=true;
            //cc.log('recv data ....');
            var func=sio.eventMap['onGame'];
             if(func)  func(data);
        }

        sio.on('connect',sio.onConnect.bind(sio));
        sio.on('disconnect',sio.onDisconnect.bind(sio));
        sio.on('onGame',sio.onData.bind(sio));
        return sio;

    }

    return wsio;
}());

module.exports=wsio;